{% extends "后台管理/template.html" %}

{% block title %}财务管理{% endblock %}

{% block css %}
<style>
    /* 描述文本溢出处理 */
    .description-cell {
        max-width: 300px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* 详情模态框中的描述文本 */
    .description-full {
        white-space: pre-wrap;
        word-break: break-word;
    }
    
    .financial-type {
        display: inline-block;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-weight: 500;
    }
    
    .type-income {
        background-color: #e8f5e9;
        color: #2e7d32;
    }
    
    .type-expense {
        background-color: #ffebee;
        color: #c62828;
    }
    
    .amount {
        font-family: monospace;
        font-weight: 600;
    }
    
    .amount.income {
        color: #2e7d32;
    }
    
    .amount.expense {
        color: #c62828;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <h4 class="fw-bold py-3 mb-4">财务管理</h4>
    
    <!-- 创建财务流水 -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0">创建财务流水</h5>
        </div>
        <div class="card-body">
            <form id="createFinancialForm" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">流水类型</label>
                    <select class="form-select" name="flow_type" required>
                        <option value="0">收入</option>
                        <option value="1">支出</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">金额</label>
                    <input type="number" class="form-control" name="amount" required step="0.01" min="0">
                </div>
                <div class="col-md-6">
                    <label class="form-label">描述</label>
                    <input type="text" class="form-control" name="description" required>
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary">创建流水</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 财务流水列表 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">财务流水列表</h5>
            <div class="d-flex gap-2">
                <span class="badge bg-label-success">总收入: ¥<span id="totalIncome">0</span></span>
                <span class="badge bg-label-danger">总支出: ¥<span id="totalExpense">0</span></span>
                <span class="badge bg-label-primary">结余: ¥<span id="balance">0</span></span>
            </div>
        </div>
        <div class="table-responsive text-nowrap">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>类型</th>
                        <th>描述</th>
                        <th>金额</th>
                        <th>操作人</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="financialList">
                    <!-- 财务流水列表将通过 JS 动态加载 -->
                </tbody>
            </table>
        </div>
        <!-- 分页 -->
        <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <div class="pagination-info">
                    总计 <span id="totalCount">0</span> 条记录
                </div>
                <ul class="pagination mb-0" id="pagination"></ul>
            </div>
        </div>
    </div>
    
    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">财务详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="fw-bold">流水编号</label>
                        <p id="detailId" class="mb-0"></p>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold">流水类型</label>
                        <p id="detailType" class="mb-0"></p>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold">金额</label>
                        <p id="detailAmount" class="mb-0"></p>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold">描述</label>
                        <p id="detailDescription" class="mb-0 description-full"></p>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold">操作人</label>
                        <p id="detailUser" class="mb-0"></p>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold">创建时间</label>
                        <p id="detailCreatedAt" class="mb-0"></p>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold">更新时间</label>
                        <p id="detailUpdatedAt" class="mb-0"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
// 当前页码
let currentPage = 1;
const pageSize = 10;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadFinancialList(1);
    initCreateForm();
});

// 初始化创建表单
function initCreateForm() {
    document.getElementById('createFinancialForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        try {
            const formData = new FormData(e.target);
            const data = {
                flow_type: formData.get('flow_type'),
                amount: formData.get('amount'),
                description: formData.get('description'),
                user_id: '{{ request.session.user.user_id }}'  // 从session获取用户ID
            };
            
            const response = await fetch('/api/financial/create/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: new URLSearchParams(data)
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                showToast('创建成功', 'success');
                e.target.reset();
                loadFinancialList(1);  // 重新加载列表
            } else {
                throw new Error(result.message || '创建失败');
            }
        } catch (error) {
            console.error('创建失败:', error);
            showToast(error.message || '创建失败', 'error');
        }
    });
}

// 加载财务流水列表
async function loadFinancialList(page) {
    try {
        const response = await fetch(`/api/financial/list/?page=${page}&page_size=${pageSize}`);
        const data = await response.json();
        
        if (data.code === 200) {
            renderFinancialList(data.data);
            updateStatistics(data.data.data);
        } else {
            throw new Error(data.message || '加载失败');
        }
    } catch (error) {
        console.error('加载失败:', error);
        showToast('加载失败', 'error');
    }
}

// 渲染财务流水列表
function renderFinancialList(data) {
    const tbody = document.getElementById('financialList');
    tbody.innerHTML = data.data.map(item => `
        <tr>
            <td>${new Date(item.created_at).toLocaleString()}</td>
            <td>
                <span class="financial-type ${item.flow_type === 0 ? 'type-income' : 'type-expense'}">
                    ${item.flow_type === 0 ? '收入' : '支出'}
                </span>
            </td>
            <td>
                <div class="description-cell" title="${item.description}">
                    ${item.description}
                </div>
            </td>
            <td>
                <span class="amount ${item.flow_type === 0 ? 'income' : 'expense'}">
                    ${item.flow_type === 0 ? '+' : '-'}¥${parseFloat(item.amount).toFixed(2)}
                </span>
            </td>
            <td>${item.user_name}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="showDetail(${JSON.stringify(item).replace(/"/g, '&quot;')})">
                    详情
                </button>
            </td>
        </tr>
    `).join('');
    
    // 更新总数和分页
    document.getElementById('totalCount').textContent = data.total;
    renderPagination(data.total, parseInt(data.page), parseInt(data.page_size));
}

// 更新统计数据
function updateStatistics(data) {
    let totalIncome = 0;
    let totalExpense = 0;
    
    data.forEach(item => {
        if (item.flow_type === 0) {
            totalIncome += parseFloat(item.amount);
        } else {
            totalExpense += parseFloat(item.amount);
        }
    });
    
    document.getElementById('totalIncome').textContent = totalIncome.toFixed(2);
    document.getElementById('totalExpense').textContent = totalExpense.toFixed(2);
    document.getElementById('balance').textContent = (totalIncome - totalExpense).toFixed(2);
}

// 渲染分页
function renderPagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    const pagination = document.getElementById('pagination');
    
    let html = '';
    
    // 上一页
    html += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0);" onclick="loadFinancialList(${currentPage - 1})">
                <i class="bx bx-chevron-left"></i>
            </a>
        </li>
    `;
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === currentPage) {
            html += `
                <li class="page-item active">
                    <a class="page-link" href="javascript:void(0);">${i}</a>
                </li>
            `;
        } else {
            html += `
                <li class="page-item">
                    <a class="page-link" href="javascript:void(0);" onclick="loadFinancialList(${i})">${i}</a>
                </li>
            `;
        }
    }
    
    // 下一页
    html += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0);" onclick="loadFinancialList(${currentPage + 1})">
                <i class="bx bx-chevron-right"></i>
            </a>
        </li>
    `;
    
    pagination.innerHTML = html;
}

// 显示详情模态框
function showDetail(item) {
    document.getElementById('detailId').textContent = item.id;
    document.getElementById('detailType').innerHTML = `
        <span class="financial-type ${item.flow_type === 0 ? 'type-income' : 'type-expense'}">
            ${item.flow_type === 0 ? '收入' : '支出'}
        </span>
    `;
    document.getElementById('detailAmount').innerHTML = `
        <span class="amount ${item.flow_type === 0 ? 'income' : 'expense'}">
            ${item.flow_type === 0 ? '+' : '-'}¥${parseFloat(item.amount).toFixed(2)}
        </span>
    `;
    document.getElementById('detailDescription').textContent = item.description;
    document.getElementById('detailUser').textContent = item.user_name;
    document.getElementById('detailCreatedAt').textContent = new Date(item.created_at).toLocaleString();
    document.getElementById('detailUpdatedAt').textContent = new Date(item.updated_at).toLocaleString();
    
    new bootstrap.Modal(document.getElementById('detailModal')).show();
}
</script>
{% endblock %}

{% block nav_left %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block NavBar %}{% endblock %}

{% block footer %}{% include '后台管理/components/Footer.html' %}{% endblock %}
